import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, Method } from 'axios';
import { IApiData } from '@/types/http';

export const instance: AxiosInstance = axios.create({
    timeout: 15000,
    baseURL: ''
});

// 添加请求拦截器
instance.interceptors.request.use(
    function (config: AxiosRequestConfig): AxiosRequestConfig {
        console.log(config);
        // 在发送请求之前做些什么
        // removePendingRequest(config);
        // addPendingRequest(config);
        // console.log(config);
        // (config.headers as any).Authorization = `Bearer ${JSON.parse(localStorage.getItem('token') as string)}`;
        // (config.headers as any).reqfrom = 'backend';
        return config;
    },
    function (error: any) {
        // console.log('request', error);
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.response.use(
    (response: AxiosResponse) => {
        // 对响应数据做点什么
        // removePendingRequest(response.config);
        // console.log('响应拦截器');
        if ((response.data as IApiData).code) {
            // return Promise.reject(response.data);
            return catchErr(response.data);
        }
        return response;
    }, catchErr
);

function catchErr(error: any) {
    console.log(error)
}

export const api = async (url: string, method: Method = "get", targrt?: object) => {
    const info = await instance({
        url,
        method,
        ...targrt
    });
    return (info.data as IApiData);
    // return info;
};
